package com.cndw.kungfu.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.BeanUtils;

import com.cndw.commons.util.BlankUtils;
import com.cndw.kungfu.comm.AccessFlag;
import com.cndw.kungfu.comm.PositionInspection;
import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsFlag;
import com.cndw.kungfu.config.ConstantsIntKey;
import com.cndw.kungfu.config.ConstantsLevel;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.config.ConstantsModel;
import com.cndw.kungfu.config.ConstantsRadio;
import com.cndw.kungfu.domain.Goods;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.domain.Scene;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.LogUtil;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.ext.WordProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.goods.MarketCenter;
import com.cndw.kungfu.model.goods.PlayerBoxs;
import com.cndw.kungfu.model.goods.PlayerMarket;
import com.cndw.kungfu.model.goods.PlayerTrade;
import com.cndw.kungfu.model.sys.LogServer;
import com.cndw.kungfu.vo.EventNotice;
import com.cndw.kungfu.vo.PlayerChangeVO;
import com.cndw.kungfu.vo.goodsvo.GoodsVO;
import com.cndw.rpg.annotation.Controller;
import com.cndw.rpg.framework.ResponseMessage;
import com.cndw.rpg.framework.Session;

/**
 * 摆摊
 * 
 * 
 * 
 * @author <a href="mailto:whz-work@163.com">汪洪州</a>
 * 
 * @since 1.0 Create on 2011-9-28
 */
@Controller
public class MarketController {

	/**
	 * 摆摊
	 * 
	 * @param session
	 * @return
	 */
	@AccessFlag(ConstantsFlag.market)
	public ResponseMessage openMarket(Session session) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());

		if (player.getDataInfo().intDataGet(ConstantsIntKey.payFree) == 1) {
			return null;
		}
		
		if (player.getDataInfo().isGoodsLock()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("player.pass.lockctrl"));
		}

		if (!player.stateContains(Constants.playerState64_market)) {
			synchronized (player) {
				if (!player.stateContains(Constants.playerState64_market)) {

					// 等级检查
					if (player.getLevel() < ConstantsLevel.lv21Market) {
						return ResponseMessage.ticpErrMsg(LanguageLib.get("market.check.level", ConstantsLevel.lv21Market));
					}

					// 场景检查
					Scene scene = Context.getSceneServer().getSceneById(player.getSceneId());
					if (!scene.isCityMain()) {
						return ResponseMessage.ticpErrMsg(LanguageLib.get("market.check.scene"));
					}

					// 摆摊状态
					player.stateAdd(Constants.playerState64_market);

					// 摆摊获取经验
					player.getDataInfo().intDataSet(ConstantsIntKey.beginDaZuo, TimeProcesser.getUnixTime());

					// 建立摊铺
					PlayerMarket market = player.getDataInfo().openMarket(player.getPlayerName(), LanguageLib.get("market.default.name", player.getPlayerName()),
							LanguageLib.get("market.default.notice"));

					market.broadcaseMarketName();
				}
			}
		}

		// 广播状态
		Context.getPlayerServer().broadcaseState(player);

		return ResponseMessage.getSuccMessage(player.getDataInfo().getMarket());
	}

	/**
	 * 查看摊位
	 * 
	 * @param session
	 * @param playerId
	 * @return
	 */
	public ResponseMessage viewMarket(Session session, long playerId) {

		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		Player currentPlayer = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (!PositionInspection.checkPlayer(player, currentPlayer)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.position.err"));
		}

		if (!player.stateContains(Constants.playerState64_market)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("market.check.exits"));
		}

		PlayerMarket market = player.getDataInfo().getMarket();
		PlayerBoxs playerBoxs = player.getPlayerBoxs();
		Map<Integer, GoodsVO> goodsMap = new HashMap<Integer, GoodsVO>();
		for (Integer[] record : market.getPriceMap().values()) {
			Goods goods = playerBoxs.getByLock(record[0]);
			if (!BlankUtils.isBlank(goods)) {
				goodsMap.put(record[1], goods.toGoodsVO());
			}
		}

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("market", market);
		resultMap.put("goodsMap", goodsMap);
		return ResponseMessage.getSuccMessage(resultMap);
	}

	/**
	 * 更改商铺名字
	 * 
	 * @param session
	 * @param name
	 * @return
	 */
	public ResponseMessage updateName(Session session, String marketName) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (!player.stateContains(Constants.playerState64_market)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("market.check.exit"));
		}

		String bad = WordProcesser.chkBadWorlds(marketName);
		if (!BlankUtils.isBlank(bad)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("mail.err.bad", bad));
		}

		PlayerMarket market = player.getDataInfo().getMarket();
		market.setMarketName(marketName);
		market.broadcaseMarketName();

		return ResponseMessage.getSuccMessage(true);
	}

	/**
	 * 更改通知
	 * 
	 * @param session
	 * @param notice
	 * @return
	 */
	public ResponseMessage updateNotice(Session session, String notice) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (!player.stateContains(Constants.playerState64_market)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("market.check.exit"));
		}

		String bad = WordProcesser.chkBadWorlds(notice);
		if (!BlankUtils.isBlank(bad)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("mail.err.bad", bad));
		}

		PlayerMarket market = player.getDataInfo().getMarket();
		market.setNotice(notice);
		market.broadcaseMarketNotice();

		return ResponseMessage.getSuccMessage(true);
	}

	/**
	 * 增加物品
	 * 
	 * @param session
	 * @param boxStorage
	 *            包袱中的位置
	 * @param marketStorage
	 *            摊位上的位置（传0由后端分配位置）
	 * @param price
	 * @param type
	 *            交易类型 1:银两，2：金币
	 * @return
	 */
	public ResponseMessage addMarketGoods(Session session, int boxStorage, int marketStorage, int price, int type) {

		if (boxStorage < 1 || marketStorage < 0 || type != 2 || price < 1) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (!player.stateContains(Constants.playerState64_market)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("market.check.exit"));
		}

		PlayerBoxs playerBoxs = player.getPlayerBoxs();
		synchronized (playerBoxs) {

			PlayerMarket market = player.getDataInfo().getMarket();

			// 检查是否到了摆摊上限
			if (market.getGoodsSize() >= ConstantsModel.marketMaxCounts) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("market.add.counts"));
			}

			// 绑定
			Goods goods = playerBoxs.get(boxStorage);
			if (BlankUtils.isBlank(goods)) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("market.add.goods"));
			}

			if (goods.getStackNum() > goods.getGoodsMode().getMaxStack()) {
				LogUtil.getMain().error("goods err " + goods.info());
				return null;// 非法状态下的物品
			}

			if (goods.getBinding() == 1) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("market.add.binding"));
			}

			Map<Integer, Integer[]> priceMap = market.getPriceMap();
			if (marketStorage != 0 && priceMap.containsKey(marketStorage)) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("market.add.storage", marketStorage));
			} else if (marketStorage == 0) {

				// 自动分配位置
				for (marketStorage = 1; marketStorage <= ConstantsModel.marketMaxCounts; marketStorage++) {
					if (!priceMap.containsKey(marketStorage)) {
						break;
					}
				}
			}

			// 锁定物品
			playerBoxs.lockGoods(boxStorage);

			// 增加物品
			market.addGoods(marketStorage, new Integer[] { boxStorage, marketStorage, price, type, goods.getStackNum() });
		}

		return ResponseMessage.getSuccMessage(marketStorage);
	}

	/**
	 * 下架物品
	 * 
	 * @param session
	 * @param marketStorage
	 * @return
	 */
	public ResponseMessage deleteMarketGoods(Session session, int marketStorage) {

		if (marketStorage < 1) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (!player.stateContains(Constants.playerState64_market)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("market.check.exit"));
		}

		PlayerBoxs playerBoxs = player.getPlayerBoxs();
		synchronized (playerBoxs) {
			PlayerMarket market = player.getDataInfo().getMarket();

			// 下架物品
			Integer[] record = market.removeGoods(marketStorage);

			// 解锁物品
			if (!BlankUtils.isBlank(record)) {
				playerBoxs.unlockGoods(record[0]);
			}
		}

		return ResponseMessage.getSuccMessage(true);
	}

	/**
	 * 调整价格
	 * 
	 * @param session
	 * @param marketStorage
	 * @param price
	 * @param type
	 * @return
	 */
	public ResponseMessage updateMarketGoodsPrice(Session session, int marketStorage, int price, int type) {

		if (marketStorage < 1 || type != 2 || price < 1) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (!player.stateContains(Constants.playerState64_market)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("market.check.exit"));
		}

		PlayerBoxs playerBoxs = player.getPlayerBoxs();
		synchronized (playerBoxs) {
			PlayerMarket market = player.getDataInfo().getMarket();
			if (market.constain(marketStorage)) {
				market.getGoods(marketStorage)[2] = price;
				market.getGoods(marketStorage)[3] = type;
			}
		}

		return ResponseMessage.getSuccMessage(true);
	}

	/**
	 * 留言
	 * 
	 * @param session
	 * @param playerId
	 *            摊主Id
	 * @param msg
	 * @return
	 */
	public ResponseMessage leaveWord(Session session, long playerId, String msg) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Player marketPlayer = Context.getPlayerServer().getByPlayerId(playerId);
		if (BlankUtils.isBlank(player) || BlankUtils.isBlank(marketPlayer)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		PlayerMarket market = marketPlayer.getDataInfo().getMarket();
		if (BlankUtils.isBlank(market)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("market.check.exits"));
		}

		market.addMessage(player.getPlayerName(), WordProcesser.filterWorlds(msg));

		EventNotice eventNotice = new EventNotice(ConstantsRadio.market, ConstantsRadio.marketMessage);
		eventNotice.put(ConstantsRadio.marketMessage, market.getMessages());
		eventNotice.broadcast(playerId);

		return ResponseMessage.getSuccMessage(market.getMessages());
	}

	/**
	 * 购买物品
	 * 
	 * @param session
	 * @param playerId
	 * @param marketStorage
	 * @param price
	 * @param counts
	 * @return
	 */
	@AccessFlag(ConstantsFlag.market)
	public ResponseMessage buyMarketGoods(Session session, long playerId, int marketStorage, int type, int price, int counts) {

		if (counts <= 0) {
			return null;
		}

		if (marketStorage < 1 || price < 1) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		if (playerId == session.getUid()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getDataInfo().isGoodsLock()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("player.pass.lockctrl"));
		}
		if (player.getDataInfo().intDataGet(ConstantsIntKey.payFree) == 1) {
			return null;
		}
		
		// 等级检查
		if (player.getLevel() < ConstantsLevel.lv21Market) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.level",ConstantsLevel.lv21Market));
		}

		Player marketPlayer = Context.getPlayerServer().getByPlayerId(playerId);
		if (BlankUtils.isBlank(player) || BlankUtils.isBlank(marketPlayer)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

//		if (!PositionInspection.checkPlayer(player, marketPlayer)) {
//			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.position.err"));
//		}

		PlayerBoxs playerBoxs = marketPlayer.getPlayerBoxs();
		synchronized (playerBoxs) {
			PlayerMarket market = marketPlayer.getDataInfo().getMarket();

			if (BlankUtils.isBlank(market)) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("market.check.exits"));
			}

			Integer[] priceObj = market.getGoods(marketStorage);

			// 物品已卖出
			if (BlankUtils.isBlank(priceObj)) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("market.sale.saled"));
			}

			// 物品价格已变更
			if (BlankUtils.isBlank(priceObj) || priceObj[2] != price) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("market.sale.price"));
			}

			// 物品支付类型已变更
			if (priceObj[3] != type) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("market.sale.type", type == 1 ? LanguageLib.get("market.sale.type2") : LanguageLib.get("market.sale.type1")));
			}

			Goods goods = playerBoxs.getByLock(priceObj[0]);
			if (counts > goods.getStackNum()) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("market.sale.counts"));
			}

			if (!player.getPlayerBoxs().checkBlack(1)) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.player.boxmin", 1));
			}

			// 扣钱
			price *= counts;
			if (price <= 0) {
				return null;
			}
			if (priceObj[3] == 1) {

				if (player.getAsset() < price) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("market.sale.asset"));
				}

				player.alterAsset(-price);
				marketPlayer.alterAsset(price);
				Context.getPlayerServer().change(PlayerChangeVO.PLAYER_ASSET, player.getAsset(), player.getPlayerId());
				Context.getPlayerServer().change(PlayerChangeVO.PLAYER_ASSET, marketPlayer.getAsset(), marketPlayer.getPlayerId());
			} else {

				if (player.getGold() < price) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("market.sale.gold"));
				}

				player.alterGold(-price);
				marketPlayer.receiveGold(price);
				Context.getPlayerServer().change(PlayerChangeVO.PLAYER_GOLD, player.getGold(), player.getPlayerId());
				Context.getPlayerServer().change(PlayerChangeVO.PLAYER_GOLD, marketPlayer.getGold(), marketPlayer.getPlayerId());
			}

			// 调整物品
			Goods tempGoods = new Goods();
			BeanUtils.copyProperties(goods, tempGoods, new String[] { "id", "playerId", "stackNum", "storagePlace" });
			tempGoods.setId(0);
			tempGoods.setStackNum(counts);
			tempGoods.setPlayerId(player.getPlayerId());
			tempGoods.setStoragePlace(0);

			player.getPlayerBoxs().add(tempGoods);

			// 调整数量
			if (goods.getStackNum() == counts) {
				playerBoxs.unlockGoods(priceObj[0]);
				playerBoxs.remove(priceObj[0]);
			} else {
				goods.setStackNum(goods.getStackNum() - counts);
				goods.commitSync();
			}

			// 出售物品
			market.saleGoods(marketStorage, counts, player.getPlayerName(), tempGoods.getGoodsMode().getName());
			player.commitSync();
			marketPlayer.commitSync();

			EventNotice eventNotice = new EventNotice(ConstantsRadio.market, ConstantsRadio.marketGoods);
			eventNotice.put(ConstantsRadio.marketGoods, priceObj);
			eventNotice.broadcast(playerId);

			// 物品售空,收摊
//			if (market.getGoodsSize() < 1) {
//				marketPlayer.getDataInfo().closeMarket();
//			}

			// 记录日志
			LogServer.recordLog(player, ConstantsLog.goods, 70008, goods.getGoodsMode().getName(), counts, priceObj[3] == 1 ? price : 0, priceObj[3] == 1 ? 0 : price,marketPlayer.getPlayerName());
			LogServer.recordLog(marketPlayer, ConstantsLog.goods, 70018, goods.getGoodsMode().getName(), counts, priceObj[3] == 1 ? price : 0, priceObj[3] == 1 ? 0 : price,player.getPlayerName());
		}

		return ResponseMessage.getSuccMessage(true);
	}

	/**
	 * 获取当前场景中所有的摊位名
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage getAllMarketName(Session session) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		Scene scene = Context.getSceneServer().getSceneById(player.getSceneId());
		Set<Long> playerIds = scene.getPlayerIds(player.getSubLine());
		Map<Long, String[]> marketMap = new HashMap<Long, String[]>();
		for (Long playerId : playerIds) {
			Player p = Context.getPlayerServer().getByPlayerId(playerId);
			PlayerMarket market = p.getDataInfo().getMarket();
			if (!BlankUtils.isBlank(market)) {
				marketMap.put(playerId, new String[] { market.getMarketName(), market.getNotice() });
			}
		}

		return ResponseMessage.getSuccMessage(marketMap);
	}

	/**
	 * 查看销售记录
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage getSaleRecord(Session session) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (BlankUtils.isBlank(player) || BlankUtils.isBlank(player.getDataInfo().getMarket())) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		return ResponseMessage.getSuccMessage(player.getDataInfo().getMarket().getSaleRecord());
	}

	/**
	 * 收摊
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage closeMarket(Session session) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (BlankUtils.isBlank(player) || BlankUtils.isBlank(player.getDataInfo().getMarket())) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		player.getDataInfo().closeMarket();

		return ResponseMessage.getSuccMessage(true);
	}

	/**
	 * 请求交易
	 * 
	 * @param session
	 * @return
	 */
	@AccessFlag(ConstantsFlag.market)
	public ResponseMessage requestTrade(Session session, long playerId) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.stateContains(Constants.playerState128_trade)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.request"));
		}
		if (player.getDataInfo().isGoodsLock()) {//物品锁定的不能请求交易
			return ResponseMessage.ticpErrMsg(LanguageLib.get("player.pass.lockctrl"));
		}
		Player tradePlayer = Context.getPlayerServer().getByPlayerId(playerId);
		if (!tradePlayer.isOnline()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.off"));
		}
		if (player.getLevel() < ConstantsLevel.lv33Trade || tradePlayer.getLevel() < ConstantsLevel.lv33Trade) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("market.err.level",ConstantsLevel.lv33Trade));
		}

		if (tradePlayer.stateContains(Constants.playerState128_trade)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.response"));
		}

		if (!PositionInspection.checkPlayer(player, tradePlayer)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.position.err"));
		}

		// 场景检查
		Scene scene = Context.getSceneServer().getSceneById(player.getSceneId());
		if (scene.isCityWall() && !scene.isCityMain()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("scene.wall.scene"));
		}

		scene = Context.getSceneServer().getSceneById(tradePlayer.getSceneId());
		if (scene.isCityWall() && !scene.isCityMain()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("scene.wall.scene"));
		}

		Context.getTcpServer().broadcastConfirm(LanguageLib.get("market.trade.requestRadio", player.getPlayerName()), "MarketController", "responseTrade", 3,
				new Object[] { player.getPlayerId() }, playerId);

		return ResponseMessage.getSuccMessage(true);
	}

	/**
	 * 响应交易
	 * 
	 * @param session
	 * @param playerId
	 * @param pass
	 * @return
	 */
	@AccessFlag(ConstantsFlag.market)
	public ResponseMessage responseTrade(Session session, long playerId, boolean pass) {

		PlayerTrade playerTrade = null;
		if (pass) {

			synchronized (this) {
				Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
				if (player.stateContains(Constants.playerState128_trade)) {
					EventNotice notice = new EventNotice(ConstantsRadio.trade, ConstantsRadio.tradeCancel);
					notice.put("message", LanguageLib.get("market.trade.response"));
					notice.put("playerId", session.getUid());
					notice.broadcast(playerId);
					return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.request"));
				}

				Player tradePlayer = Context.getPlayerServer().getByPlayerId(playerId);
				if (!tradePlayer.isOnline()) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.off"));
				}

				if (tradePlayer.stateContains(Constants.playerState128_trade)) {
					EventNotice notice = new EventNotice(ConstantsRadio.trade, ConstantsRadio.tradeCancel);
					notice.put("message", LanguageLib.get("market.trade.request"));
					notice.put("playerId", session.getUid());
					notice.broadcast(playerId);
					return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.response"));
				}

				// 场景检查
				Scene scene = Context.getSceneServer().getSceneById(player.getSceneId());
				if (scene.isCityWall() && !scene.isCityMain()) {
					EventNotice notice = new EventNotice(ConstantsRadio.trade, ConstantsRadio.tradeCancel);
					notice.put("message", LanguageLib.get("scene.wall.scene"));
					notice.put("playerId", session.getUid());
					notice.broadcast(playerId);
					return ResponseMessage.ticpErrMsg(LanguageLib.get("scene.wall.scene"));
				}

				scene = Context.getSceneServer().getSceneById(tradePlayer.getSceneId());
				if (scene.isCityWall() && !scene.isCityMain()) {
					EventNotice notice = new EventNotice(ConstantsRadio.trade, ConstantsRadio.tradeCancel);
					notice.put("message", LanguageLib.get("scene.wall.scene"));
					notice.put("playerId", session.getUid());
					notice.broadcast(playerId);
					return ResponseMessage.ticpErrMsg(LanguageLib.get("scene.wall.scene"));
				}

				if (!PositionInspection.checkPlayer(player, tradePlayer)) {
					EventNotice notice = new EventNotice(ConstantsRadio.trade, ConstantsRadio.tradeCancel);
					notice.put("message", LanguageLib.get("comm.position.err"));
					notice.put("playerId", session.getUid());
					notice.broadcast(playerId);
					return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.position.err"));
				}

				playerTrade = new PlayerTrade(tradePlayer, player);

				player.stateAdd(Constants.playerState128_trade);
				tradePlayer.stateAdd(Constants.playerState128_trade);
			}

			Context.getDataServer().getPlayerTradeMap().put(playerId, playerTrade);
			Context.getDataServer().getPlayerTradeMap().put(session.getUid(), playerTrade);
		}

		EventNotice eventNotice = new EventNotice(ConstantsRadio.trade, ConstantsRadio.tradeResponse);
		eventNotice.put("playerTrade", BlankUtils.isBlank(playerTrade) ? session.getUid() : playerTrade);
		eventNotice.broadcast(playerId, session.getUid());

		return ResponseMessage.getSuccMessage(true);
	}

	/**
	 * 取消交易
	 * 
	 * @param session
	 * @param id
	 * @return
	 */
	public ResponseMessage cancelTrade(Session session) {

		PlayerTrade trade = Context.getDataServer().getPlayerTradeMap().get(session.getUid());

		if (BlankUtils.isBlank(trade) || (trade.getReqPlayerId() != session.getUid() && trade.getRespPlayerId() != session.getUid())) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		trade.canelTrade(LanguageLib.get("market.trade.cancel"), session.getUid());

		return ResponseMessage.getSuccMessage(true);
	}

	/**
	 * 拖物品到交易框
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage addTradeGoods(Session session, int storage) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getDataInfo().isGoodsLock()) {//物品锁定的不能请求交易
			return ResponseMessage.ticpErrMsg(LanguageLib.get("player.pass.lockctrl"));
		}		
		if (player.getDataInfo().intDataGet(ConstantsIntKey.payFree) == 1) {
			return null;
		}
		
		PlayerTrade trade = Context.getDataServer().getPlayerTradeMap().get(session.getUid());
		if (BlankUtils.isBlank(trade)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		if (trade.isLock(session.getUid())) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.lock"));
		}

		// 检查是否到了上限
		List<Integer> storages = trade.getGoods().get(session.getUid());
		if (storages.size() >= ConstantsModel.marketTradeMaxCounts) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.maxCounts", ConstantsModel.marketTradeMaxCounts));
		}

		// 原有物品
		List<GoodsVO> goodsVOs = new ArrayList<GoodsVO>();
		PlayerBoxs playerBoxs = Context.getPlayerServer().getByPlayerId(session.getUid()).getPlayerBoxs();
		for (int storagePlace : storages) {
			goodsVOs.add(playerBoxs.getByLock(storagePlace).toGoodsVO());
		}

		// 新增的物品
		synchronized (playerBoxs) {
			if (playerBoxs.containsKey(storage)) {
				Goods g = playerBoxs.getByLock(storage);

				if (g.getBinding() == 1) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.binding"));
				}

				playerBoxs.lockGoods(storage);
				storages.add(storage);
				goodsVOs.add(g.toGoodsVO());

				EventNotice eventNotice = new EventNotice(ConstantsRadio.trade, ConstantsRadio.tradeUpdate);
				eventNotice.put("goodsVOs", goodsVOs);
				eventNotice.broadcast(trade.getPlayerId(session.getUid()));
			}
		}
		return ResponseMessage.getSuccMessage(goodsVOs);
	}

	/**
	 * 移出物品
	 * 
	 * @param session
	 * @param id
	 * @param storage
	 * @return
	 */
	public ResponseMessage deleteTradeGoods(Session session, int storage) {

		PlayerTrade trade = Context.getDataServer().getPlayerTradeMap().get(session.getUid());
		if (BlankUtils.isBlank(trade)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		if (trade.isLock(session.getUid())) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.lock"));
		}

		List<Integer> storages = trade.getGoods().get(session.getUid());
		PlayerBoxs playerBoxs = Context.getPlayerServer().getByPlayerId(session.getUid()).getPlayerBoxs();
		storages.remove(Integer.valueOf(storage));
		playerBoxs.unlockGoods(storage);

		List<GoodsVO> goodsVOs = new ArrayList<GoodsVO>();
		for (int storagePlace : storages) {
			goodsVOs.add(playerBoxs.getByLock(storagePlace).toGoodsVO());
		}

		EventNotice eventNotice = new EventNotice(ConstantsRadio.trade, ConstantsRadio.tradeUpdate);
		eventNotice.put("goodsVOs", goodsVOs);
		eventNotice.broadcast(trade.getPlayerId(session.getUid()));

		return ResponseMessage.getSuccMessage(goodsVOs);
	}

	/**
	 * 输入交易框的银两
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage updateTradeAsset(Session session, int asset) {

		if (asset < 0) {
			return null;
		}

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getDataInfo().isGoodsLock()) {//物品锁定的不能请求交易
			return ResponseMessage.ticpErrMsg(LanguageLib.get("player.pass.lockctrl"));
		}		
		if (player.getDataInfo().intDataGet(ConstantsIntKey.payFree) == 1) {
			return null;
		}
		
		if (player.getAsset() < asset) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.asset"));
		}

		PlayerTrade trade = Context.getDataServer().getPlayerTradeMap().get(session.getUid());
		if (BlankUtils.isBlank(trade)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		synchronized (trade) {
			if (trade.isLock(session.getUid())) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.lock"));
			}

			trade.getAsset().get(session.getUid())[0] = asset;

			EventNotice eventNotice = new EventNotice(ConstantsRadio.trade, ConstantsRadio.tradeUpdate);
			eventNotice.put("asset", trade.getAsset().get(session.getUid()));
			eventNotice.broadcast(trade.getPlayerId(session.getUid()));
		}

		return ResponseMessage.getSuccMessage(trade.getAsset().get(session.getUid()));
	}

	/**
	 * 输入交易框的金币
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage updateTradeGold(Session session, int gold) {

		if (gold < 0) {
			return null;
		}

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getDataInfo().isGoodsLock()) {//物品锁定的不能请求交易
			return ResponseMessage.ticpErrMsg(LanguageLib.get("player.pass.lockctrl"));
		}		
		if (player.getDataInfo().intDataGet(ConstantsIntKey.payFree) == 1) {
			return null;
		}
		
		if (player.getGold() < gold) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.gold"));
		}

		PlayerTrade trade = Context.getDataServer().getPlayerTradeMap().get(session.getUid());
		if (BlankUtils.isBlank(trade)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		synchronized (trade) {
			if (trade.isLock(session.getUid())) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.lock"));
			}

			trade.getAsset().get(session.getUid())[1] = gold;

			EventNotice eventNotice = new EventNotice(ConstantsRadio.trade, ConstantsRadio.tradeUpdate);
			eventNotice.put("asset", trade.getAsset().get(session.getUid()));
			eventNotice.broadcast(trade.getPlayerId(session.getUid()));
		}

		return ResponseMessage.getSuccMessage(trade.getAsset().get(session.getUid()));
	}

	/**
	 * 锁定交易
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage lockTrade(Session session) {

		PlayerTrade trade = Context.getDataServer().getPlayerTradeMap().get(session.getUid());
		if (BlankUtils.isBlank(trade)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		if (trade.hasLock() && trade.getAsset().get(trade.getRespPlayerId())[0] == 0 && trade.getAsset().get(trade.getRespPlayerId())[1] == 0
				&& trade.getAsset().get(trade.getReqPlayerId())[1] == 0 && trade.getAsset().get(trade.getReqPlayerId())[0] == 0
				&& trade.getGoods().get(trade.getRespPlayerId()).isEmpty() && trade.getGoods().get(trade.getReqPlayerId()).isEmpty()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.lockerr"));
		}

		trade.lock(session.getUid());

		new EventNotice(ConstantsRadio.trade, ConstantsRadio.tradeLock).broadcast(trade.getPlayerId(session.getUid()));

		return ResponseMessage.getSuccMessage(true);
	}

	/**
	 * 确认交易
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage confirmTrade(Session session) {

		PlayerTrade trade = Context.getDataServer().getPlayerTradeMap().get(session.getUid());
		if (BlankUtils.isBlank(trade)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}
		if (!trade.allLock()) {			
			return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.alllock"));
		}

		trade.comfirm(session.getUid()); // 确认
		long reqPlayerId = session.getUid();
		long respPlayerId = trade.getPlayerId(session.getUid());

		// 判断是否双方都确认
		if (trade.getStatus() == 15) {

			Player reqPlayer = Context.getPlayerServer().getByPlayerId(reqPlayerId);
			Player respPlayer = Context.getPlayerServer().getByPlayerId(respPlayerId);
			PlayerBoxs reqBoxs = reqPlayer.getPlayerBoxs();
			PlayerBoxs respBoxs = respPlayer.getPlayerBoxs();

			if (!PositionInspection.checkPlayer(reqPlayer, respPlayer)) {
				trade.closeTrade(LanguageLib.get("comm.position.err"), ConstantsRadio.tradeCancel, respPlayerId);
				return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.position.err"), respPlayerId);
			}

			if (reqPlayer.getAsset() < trade.getAsset().get(reqPlayerId)[0] || respPlayer.getAsset() < trade.getAsset().get(respPlayerId)[0]) {
				trade.closeTrade(LanguageLib.get("market.trade.gold"), ConstantsRadio.tradeCancel, respPlayerId);
				return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.gold"), respPlayerId);
			}
			if (reqPlayer.getGold() < trade.getAsset().get(reqPlayerId)[1] || respPlayer.getGold() < trade.getAsset().get(respPlayerId)[1]) {
				trade.closeTrade(LanguageLib.get("market.trade.asset"), ConstantsRadio.tradeCancel, respPlayerId);
				return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.asset"), respPlayerId);
			}

			int repSize = trade.getGoods().get(reqPlayerId).size();
			int respSize = trade.getGoods().get(respPlayerId).size();
			if (respSize > repSize && !reqBoxs.checkBlack(respSize - repSize)) {
				trade.closeTrade(LanguageLib.get("market.trade.box2"), ConstantsRadio.tradeCancel, respPlayerId);
				return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.player.boxmin", respSize - repSize), respPlayerId);
			}

			if (repSize > respSize && !respBoxs.checkBlack(repSize - respSize)) {
				trade.closeTrade(LanguageLib.get("comm.player.boxmin", repSize - respSize), ConstantsRadio.tradeCancel, respPlayerId);
				return ResponseMessage.ticpErrMsg(LanguageLib.get("market.trade.box2"), respPlayerId);
			}

			// 物品交易
			List<Goods> reqRemove = new ArrayList<Goods>();
			List<Goods> respRemove = new ArrayList<Goods>();
			StringBuilder req = new StringBuilder();
			StringBuilder resp = new StringBuilder();
			for (Integer storage : trade.getGoods().get(reqPlayerId)) {
				int counts = reqBoxs.getByLock(storage).getStackNum();
				Goods goods = reqBoxs.remove(storage);
				goods.setPlayerId(respPlayerId);
				goods.setStoragePlace(0);
				goods.setStackNum(counts);
				reqRemove.add(goods);
				reqBoxs.unlockGoods(storage);
				resp.append(goods.getGoodsMode().getName()).append(":");
				resp.append(counts).append(",");
			}
			for (Integer storage : trade.getGoods().get(respPlayerId)) {
				int counts = respBoxs.getByLock(storage).getStackNum();
				Goods goods = respBoxs.remove(storage);
				goods.setPlayerId(reqPlayerId);
				goods.setStoragePlace(0);
				goods.setStackNum(counts);
				respRemove.add(goods);
				respBoxs.unlockGoods(storage);
				req.append(goods.getGoodsMode().getName()).append(":");
				req.append(counts).append(",");
			}

			for (Goods g : reqRemove) {
				respBoxs.add(g);
			}

			for (Goods g : respRemove) {
				reqBoxs.add(g);
			}

			// 银两交易
			// reqPlayer.alterAsset(-trade.getAsset().get(reqPlayerId)[0]);
			// respPlayer.alterAsset(trade.getAsset().get(reqPlayerId)[0]);
			// respPlayer.alterAsset(-trade.getAsset().get(respPlayerId)[0]);
			// reqPlayer.alterAsset(trade.getAsset().get(respPlayerId)[0]);

			// 金币交易
			reqPlayer.alterGold(-trade.getAsset().get(reqPlayerId)[1]);
			respPlayer.receiveGold(trade.getAsset().get(reqPlayerId)[1]);
			respPlayer.alterGold(-trade.getAsset().get(respPlayerId)[1]);
			reqPlayer.receiveGold(trade.getAsset().get(respPlayerId)[1]);

			// 广播银两和金币
			PlayerChangeVO changeVo = new PlayerChangeVO();
			// changeVo.put(PlayerReceiveVO.RECEIVE_ASSET,
			// reqPlayer.getAsset());
			changeVo.put(PlayerChangeVO.PLAYER_GOLD, reqPlayer.getGold());
			changeVo.broadcast(reqPlayer.getPlayerId());

			changeVo = new PlayerChangeVO();
			// changeVo.put(PlayerReceiveVO.RECEIVE_ASSET,
			// respPlayer.getAsset());
			changeVo.put(PlayerChangeVO.PLAYER_GOLD, respPlayer.getGold());
			changeVo.broadcast(respPlayer.getPlayerId());

			// 同步
			reqPlayer.commitSync();
			respPlayer.commitSync();

			// 记录日志
			int reqGetAsset = trade.getAsset().get(respPlayerId)[0]; // 请求者获得银两
			int reqLostAsset = trade.getAsset().get(reqPlayerId)[0]; // 请求者失去银两
			int reqGetGold = trade.getAsset().get(respPlayerId)[1]; // 请求者获得元宝
			int reqLostGold = trade.getAsset().get(reqPlayerId)[1]; // 请求者失去银两
			LogServer.recordLog(reqPlayer, ConstantsLog.goods, 70009, respPlayer.getPlayerName(), reqGetAsset, reqGetGold, req.toString(), reqLostAsset, reqLostGold,
					resp.toString());
			LogServer.recordLog(respPlayer, ConstantsLog.goods, 70009, reqPlayer.getPlayerName(), reqLostAsset, reqLostGold, resp.toString(), reqGetAsset, reqGetGold,
					req.toString());

			trade.closeTrade(LanguageLib.get("market.trade.finish"), ConstantsRadio.tradeConfirm, respPlayerId);
			return ResponseMessage.getSuccMessage(true);
		} else {
			new EventNotice(ConstantsRadio.trade, ConstantsRadio.tradeConfirm).broadcast(respPlayerId);
			return ResponseMessage.getSuccMessage(false);
		}
	}
	
	public ResponseMessage marketCenterShow(Session session, int type) {
		if (type < 0) {
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", MarketCenter.getByType(type));
		return ResponseMessage.getSuccMessage(map);
	}
}
